package com.zwy.Shopping.servlet_;

import com.zwy.Shopping.dao.OrderDao;
import com.zwy.Shopping.dao.OrderItemDao;
import com.zwy.Shopping.dao.impl.OrderDaoImpl;
import com.zwy.Shopping.dao.impl.OrderItemDaoImpl;
import com.zwy.Shopping.model.CartItem;
import com.zwy.Shopping.model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

@WebServlet("/buy_all_in_cartItem")
public class BuyAllProductInCartItemServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得支付金额total,userId,获得
        String totalStr = request.getParameter("total");
        User user = (User) request.getSession().getAttribute("user");
        int userId = user.getId();
        BigDecimal total = new BigDecimal(totalStr);
        if (!total.equals(new BigDecimal(0))) {
            //形成订单
            OrderDao orderDao = new OrderDaoImpl();
            int orderId = orderDao.generateOrder(userId, total);

            //订单明细的生成
            OrderItemDao orderItemDao = new OrderItemDaoImpl();
            ServletContext application = this.getServletContext();
            List<CartItem> cartItemList = (List<CartItem>) application.getAttribute("cartItemList");
            //使用了迭代器来访问list中的元素
            Iterator<CartItem> iterator = cartItemList.iterator();
            while (iterator.hasNext()) {
                CartItem cartItem = iterator.next();
                if (cartItem.getUserId() == userId) {
                    orderItemDao.generateOrderItem(orderId, cartItem.getProduct().getId(), cartItem.getProduct().getPrice(), cartItem.getQuantity());
                    iterator.remove(); // 使用迭代器安全地删除元素
                }
            }
// 更新ServletContext中的"cartItemList"属性
            application.setAttribute("cartItemList", cartItemList);
// 更新ServletContext中的"cartItemNum"属性
            application.setAttribute("cartItemNum", 0);

        }
    }
}